package me.leiusual.sharing.ui.cart.adapter

import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.view_holder_cart_order_parent.*
import me.leiusual.sharing.api.model.cartdetail.Cart
import me.leiusual.sharing.util.extension.spToPx
import me.leiusual.sharing.util.extension.toSpanned

/**
 * author: leiusual
 * create on: 2019-07-31
 * description:
 */
class CartOrderParentViewHolder(
    override val containerView: View
) : RecyclerView.ViewHolder(containerView), LayoutContainer, TextWatcher {

  private lateinit var cart: Cart

  init {
    recycler_view.adapter = CartOrderChildAdapter()
    edit_text_memo.addTextChangedListener(this)
  }

  fun bind(cart: Cart) {
    this.cart = cart

    // 店铺
    text_view_store_name.text = cart.storeName

    // 合计
    var totalRmb = 0.0
    var totalJfb = 0.0
    var totalYun = 0.0
    cart.cartList.forEach {
      it.priceVos.forEach { priceVo ->
        when (priceVo.coinType) {
          "RMB" -> totalRmb += priceVo.pointCoin * it.quantity
          else -> totalJfb += priceVo.pointCoin * it.quantity
        }
      }
      totalYun += it.independentFreight
    }
    val size = 8f.spToPx(containerView.context)
    val builder = StringBuilder()
    builder.append("""店铺费用合计：""")
    builder.append("""<font color="red">""")
    builder.append("""<size_$size>￥</size_$size>""")
    builder.append(totalRmb)
    if (totalJfb > 0) {
      builder.append("""  <size_$size>分</size_$size>""")
      builder.append(totalJfb)
    }
    if (totalYun > 0) {
      builder.append("""  <size_$size>运</size_$size>""")
      builder.append(totalYun)
    }
    builder.append("""</font>""")
    text_view_total.text = builder.toString().toSpanned()

    // 商品
    val adapter = recycler_view.adapter as CartOrderChildAdapter
    adapter.submitList(cart.cartList)

    // 留言
    edit_text_memo.setText(cart.memo)
  }

  override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
  }

  override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
  }

  override fun afterTextChanged(s: Editable?) {
    cart.memo = s.toString()
  }
}